package org.his.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.his.dao.MenuFotonDao;
import org.his.dao.UserDao;
import org.his.pojo.quanxuan.MenuFoton;
import org.his.pojo.quanxuan.User;
import org.his.utils.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UserDao userDao;

    @Autowired
    private MenuFotonDao menuFotonDao;


    @RequestMapping(value = "/login",method= RequestMethod.GET)
    public String login()throws Exception{
        return "login";
    }

    @RequestMapping(value = "/login",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> login(HttpServletRequest request)throws Exception{
        Map<String,Object> map = new HashMap<>();
        System.out.println("认证失败了吧！来我这了吧");
        String exceptionName = request.getAttribute("shiroLoginFailure").toString();
        if (exceptionName.equals(UnknownAccountException.class.getName())){
            map.put("code",1);
            map.put("msg","用户名或密码不正确!");
            return map;
        }else if(exceptionName.equals(IncorrectCredentialsException.class.getName())){
            map.put("code",2);
            map.put("msg","用户名或密码不正确!");
            return map;
        }
        return null;




    }

    @RequestMapping("/success")
    @ResponseBody
    public  Map<String,Object> success(HttpSession session) throws Exception{
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        session.setAttribute(Common.LOGIN_USER,user);
        List<MenuFoton> menuFotonList = menuFotonDao.getMenuFotonByUserId(user.getUserid());
        session.setAttribute(Common.LOGIN_USER_MENUFOTON,menuFotonList);
//
//        List<SysPermission> list = sysPermissionDao.getPersByUserId(sysUser.getId());
//        session.setAttribute(Constants.LOGIN_USER_PERS,list);



        return map;
    }
    @RequestMapping(value = "/main",method= RequestMethod.GET)
    public String main()throws Exception{
        return "main";
    }
}
